(function ($) {
    window.onload = function () {
        //如果不是编辑界面，那么就不执行下面的操作
        if (window.location.pathname == '/storage/app/') {
            return;
        }

        $('#id_version').attr("disabled", true);
        $('.submit-row').click(beforeSubmit);

        firebase.initializeApp(config);

        var auth = firebase.auth();
        var storageRef = firebase.storage().ref();

        $('#id_name').after('<input type="button" id="id_json" class="button" name="json" value="Json"></input>') //插入按钮
        $('#id_json').css("marginLeft", "8px")
        $('#id_json').click(handleJson);

        $('#id_json').after('<input type="button" id="id_publish" class="button" name="publish" value="Publish"></input>') //插入按钮
        $('#id_publish').css("marginLeft", "8px")
        $('#id_publish').click(handlePublish);
        $('#id_publish').after('<label id="process" style="float:right"></label>');

        var levels;
        document.getElementById('id_json').disabled = true;
        let app_name = document.getElementById('id_name').value
        $.get("/ajax/check_levels_sound/", {'appname': app_name}, function (ret) {
            document.getElementById('id_json').disabled = false;
            levels = ret;
        })

        document.getElementById('id_publish').disabled = true;

        auth.onAuthStateChanged(function (user) {
            if (user) {               
                console.log('Anonymous user signed-in.', user);
                document.getElementById('id_publish').disabled = false;
            } else {
                console.log('There was no anonymous session. Creating a new anonymous user.');
                auth.signInAnonymously();
            }
        });

        function beforeSubmit(evt) {
            $('#id_version').attr("disabled", false);
        }
        
        function handlePublish(evt) {
            if (levels.length != 0) {
                log = 'The following level DO NOT have sound: '
                for (let index = 0; index < levels.length; index++) {
                    log += levels[index].name + ", ";
                }
                alert(log);
                return;
            }

            document.getElementById('id_publish').disabled = true;
            publish('app')

            let value = parseInt(document.getElementById('id_version').value);
            document.getElementById('id_version').value = value + 1;
        }

        function publish(name) {
            let app_name = document.getElementById('id_name').value
            $.get("/ajax/publish/", {'filename': name, 'appname': app_name}, function (ret) {
                let id_name = document.getElementById('id_name').value
                let json = JSON.stringify(ret)
                storageRef.child('diff/data/' + id_name + '/' + name + '.json').putString(json).then(function (snapshot) {
                    if (name == 'app') {
                        publish('level')
                    } else if (name == 'level') {
                        alert('Publish succeed.')
                    }
                }).catch(function (error) {
                    alert('Publish failed.')
                    document.getElementById('id_publish').disabled = false;
                });
            })
        }

        function jsonToBuffer(json) {
            let string = JSON.stringify(json)
            let arrayBuffer = new ArrayBuffer(string.length * 1)
            let newUint = new Uint8Array(arrayBuffer);
            newUint.forEach((_, i) => {
                newUint[i] = string.charCodeAt(i);
            });
            return newUint;
        }

        function handleJson(evt) {
            if (levels.length != 0) {
                log = 'The following level DO NOT have sound: '
                for (let index = 0; index < levels.length; index++) {
                    log += levels[index].name + ", ";
                }
                alert(log);
                return;
            }

            let zip = new JSZip();
            let app_name = document.getElementById('id_name').value
            $.get("/ajax/publish/", {'filename': 'app', 'appname': app_name, 'additive': false}, function (ret) {
                zip.file('app.json', jsonToBuffer(ret), { binary: true });
                $.get("/ajax/publish/", {'filename': 'level', 'appname': app_name}, function (ret) {                            
                    zip.file('level.json', jsonToBuffer(ret), { binary: true });
                    saveAs(zip.generate({ type: "blob" }), app_name + '-json.zip');
                })
            })
        }
    }
})(django.jQuery);
